<?php
namespace App\Http\Controllers\Admin\system;

use App\Http\Controllers\Admin\CommonController;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Permission;
use Route;
use Entrust;

class PermissionController extends CommonController
{
    function __construct()
    {
        parent::__construct();
        // 自定义权限中间件

        view()->share([
            '_system' => 'active',
            '_permission' => "active",
            'permissions' => Permission::get_permissions()
        ]);

    }

    //显示权限管理首页
    public function index(Request $request)
    {
        return view('admin.system.permission.index',['count'=>Permission::count()]);
    }

    //添加权限
    public function create(Request $request)
    {
        $pid=!empty($request->pid)?$request->pid:'-1';
        return view('admin.system.permission.create',['pid'=>$pid]);
    }

    //存储权限
    public function store(Request $request)
    {
//        return $request->all();
        Permission::create($request->all()); //把所有提交上来的数据添加到数据库
        return redirect(route('system.permission.index'))->with('success','新增权限成功');
    }


    public function edit($id)
    {
        $permission=Permission::find($id);
        return view('admin.system.permission.edit')->with('permission',$permission);
    }


    public function update(Request $request, $id)
    {
//        return $request->all();
        $permission=Permission::find($id);
        $permission->update($request->all()); //修改request上提交的所有数据
        return redirect(route('system.permission.index'))->with('success','修改权限成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if (!Permission::check_children($id)) {
            return back()->with('error', '当前栏目有子栏目，请先将子栏目删除后再尝试删除~');
        }

        Permission::destroy($id);
        Permission::clear();
        return back()->with('success','删除权限成功');
    }

}
